import type { InputProps } from 'antd';
import { Input } from 'antd';
import type { ChangeEvent, FocusEvent, KeyboardEvent } from 'react';
import type { PluginCtx } from 'sula/es/types/ctx';
import { useState } from 'react';
import isFunction from 'lodash/isFunction';
import { history } from 'umi';

type Props = InputProps & {
  onChange?: (value: any) => void;
  pressEnterTriggerHistoryQueryName?: string | (() => string);
  pressEnterTriggerSubmit?: boolean;
  ctx?: PluginCtx;
};

const EnhancedInput: React.FC<Props> = ({
  value,
  onChange,
  onPressEnter,
  pressEnterTriggerHistoryQueryName,
  pressEnterTriggerSubmit = false,
  ...rest
}) => {
  const { ctx = undefined } = rest;
  const [data, setData] = useState('');

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (onChange) {
      onChange(e.target.value);
    }
  };

  const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
    const ret = e.target.value.replaceAll('\\xc2\\xa', ' ').trim();
    setData(ret);
    if (onChange) {
      onChange(ret);
    }
  };
  const handlePressEnter = (event: KeyboardEvent<HTMLInputElement>) => {
    onPressEnter?.(event);
    const outputValue = event.target.value;
    if (pressEnterTriggerSubmit && ctx && ctx.form) {
      let queryName = pressEnterTriggerHistoryQueryName || ctx.name;
      if (isFunction(pressEnterTriggerHistoryQueryName)) {
        queryName = pressEnterTriggerHistoryQueryName();
      }
      const query = { ...history.location.query, [queryName]: outputValue };
      if (outputValue === '' || outputValue === undefined) {
        delete query[queryName];
      }
      history.replace({ query });
      ctx.form.submit();
    }
  };
  return (
    <Input
      value={value !== undefined ? value : data}
      onChange={handleChange}
      onBlur={handleBlur}
      onPressEnter={handlePressEnter}
      {...rest}
    />
  );
};

export default EnhancedInput;
